//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer, useLocalObservable } from 'mobx-react';
import { LocalDevflowTrigerStore } from "@/stores/local";
import { useStores } from "@/hooks";
import { Button, message, Modal, Popover, Space, Table } from "antd";
import type { ColumnsType } from 'antd/lib/table';
import type { TrigerInfo } from "@/api/project_triger";
import { update_name, remove as remove_triger, reset_secret as reset_triger_secret } from "@/api/project_triger";
import { EditText } from "@/components/EditCell/EditText";
import { CopyOutlined, MoreOutlined } from "@ant-design/icons";
import { writeText } from "@tauri-apps/api/clipboard";
import { request } from "@/utils/request";
import TypeAttrDescModal from "./components/TypeAttrDescModal";
import { open as shell_open } from '@tauri-apps/api/shell';

const TrigerList = () => {
    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');
    const appStore = useStores('appStore');

    const trigerStore = useLocalObservable(() => new LocalDevflowTrigerStore(projectStore.curProjectId, 20));

    const [removeTrigerInfo, setRemoveTrigerInfo] = useState<TrigerInfo | null>(null);
    const [resetSecretTrigerInfo, setResetSecretTrigerInfo] = useState<TrigerInfo | null>(null);
    const [showAttrTypeId, setShowAttrTypeId] = useState("");

    const removeTriger = async () => {
        if (removeTrigerInfo == null) {
            return;
        }
        await request(remove_triger({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            triger_id: removeTrigerInfo.triger_id,
        }));
        message.info("删除成功");
        setRemoveTrigerInfo(null);
    };

    const resetTrigerSecret = async () => {
        if (resetSecretTrigerInfo == null) {
            return;
        }
        await request(reset_triger_secret({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            triger_id: resetSecretTrigerInfo.triger_id,
        }));
        message.info("重置成功");
        setResetSecretTrigerInfo(null);
    };

    const columns: ColumnsType<TrigerInfo> = [
        {
            title: "名称",
            width: 180,
            render: (_, row: TrigerInfo) => (
                <EditText editable={projectStore.isAdmin && !projectStore.isClosed}
                    content={row.triger_name} onChange={async value => {
                        if (value.trim() == "") {
                            return false;
                        }
                        try {
                            await request(update_name({
                                session_id: userStore.sessionId,
                                project_id: projectStore.curProjectId,
                                triger_id: row.triger_id,
                                triger_name: value.trim(),
                            }));
                            message.info("修改成功");
                            return true;
                        } catch (e) {
                            console.log(e);
                            return false;
                        }
                    }} showEditIcon />
            ),
        },
        {
            title: "webhook地址",
            render: (_, row: TrigerInfo) => (
                <div>
                    <span>{`${appStore.clientCfg?.serv_http_addr ?? ""}/webhook/${row.type_id}/${row.triger_id}`}</span>
                    <Button type="link" icon={<CopyOutlined />} title="复制地址" onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        writeText(`${appStore.clientCfg?.serv_http_addr ?? ""}/webhook/${row.type_id}/${row.triger_id}`).then(() => {
                            message.info("复制成功");
                        });
                    }} />
                </div>
            ),
        },
        {
            title: "类型",
            width: 60,
            render: (_, row: TrigerInfo) => (
                <a onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    if (row.triger_id == "atomgit") {
                        shell_open("https://atomgit.com/");
                    } else if (row.triger_id == "gitcode") {
                        shell_open("https://gitcode.com/");
                    } else if (row.triger_id == "gitee") {
                        shell_open("https://gitee.com/");
                    }
                }}>{row.type_id}</a>
            )
        },
        {
            title: "消息",
            width: 50,
            render: (_, row: TrigerInfo) => (
                <a onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    projectStore.projectHome.curTriger = row;
                }}>{row.msg_count}</a>
            ),
        },
        {
            title: "操作",
            width: 150,
            render: (_, row: TrigerInfo) => (
                <Space>
                    <Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        projectStore.projectHome.curTriger = row;
                    }}>查看详情</Button>
                    {projectStore.isAdmin && row.has_secret && (
                        <Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            writeText(row.secret).then(() => message.info("复制成功"));
                        }}>复制密码</Button>
                    )}
                    <Popover placement="bottom" trigger="click" content={
                        <Space direction="vertical">
                            {projectStore.isAdmin && !projectStore.isClosed && row.has_secret && (
                                <Button type="link" onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setResetSecretTrigerInfo(row);
                                }}>重置密码</Button>
                            )}
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowAttrTypeId(row.type_id);
                            }}>属性定义</Button>
                            {projectStore.isAdmin && !projectStore.isClosed && (
                                <Button type="link" danger onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setRemoveTrigerInfo(row);
                                }}>删除</Button>
                            )}

                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>
                </Space>
            ),
        }
    ];

    useEffect(() => {
        return () => {
            trigerStore.unlisten();
        };
    }, []);

    return (
        <>
            <Table rowKey="triger_id" dataSource={trigerStore.itemList} columns={columns}
                style={{ paddingLeft: "10px" }}
                pagination={{ total: trigerStore.totalCount, pageSize: trigerStore.pageSize, current: trigerStore.curPage + 1, onChange: page => trigerStore.curPage = page - 1, hideOnSinglePage: true }} />
            {removeTrigerInfo != null && (
                <Modal open title="删除接收器" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveTrigerInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeTriger();
                    }}>
                    是否删除接收器&nbsp;{removeTrigerInfo.triger_name}&nbsp;?
                </Modal>
            )}
            {showAttrTypeId != "" && (
                <TypeAttrDescModal typeId={showAttrTypeId} onClose={() => setShowAttrTypeId("")} />
            )}
            {resetSecretTrigerInfo != null && (
                <Modal open title="重置密码" mask={false}
                    okText="重置" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setResetSecretTrigerInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        resetTrigerSecret();
                    }}>
                    是否重置接收器&nbsp;{resetSecretTrigerInfo.triger_name}&nbsp;密码?
                </Modal>
            )}
        </>
    );
};

export default observer(TrigerList);